#!/bin/sh
#
# GoodJob background runner
# Authors: Jesper Grann Laursen <powerlauer@gmail.com>
#
# Project: https://github.com/bensheldon/good_job
#
# PROVIDE: goodjob
# REQUIRE: NETWORKING SERVERS DAEMON LOGIN
# KEYWORD: shutdown
#
# Requirements:
#
# This file should be placed into: /usr/local/etc/rc.d/goodjob
#
# Add the following lines to /etc/rc.conf to enable goodjob:
#
# Required:
# goodjob_enable="YES"
#
# Optional:
# goodjob_dir
# goodjob_user
# goodjob_env
# goodjob_poll_interval

. /etc/rc.subr

name=goodjob
rcvar=goodjob_enable
extra_commands="status restart"

load_rc_config $name

###############################################################################
# Set default values (overrides should be placed in /etc/rc.conf )
###############################################################################

: ${goodjob_enable:=NO}
: ${goodjob_dir:=/opt/www/goodjob}
: ${goodjob_user:=deployment}
: ${goodjob_env:=production}
: ${goodjob_poll_interval:=5}

required_dirs="${goodjob_dir}"

_grep=`command -v grep 2>&1 >/dev/null && command -v grep`
_pgrep=`command -v pgrep 2>&1 >/dev/null && command -v pgrep`
_sh=`command -v sh 2>&1 >/dev/null && command -v sh`
_ps=`command -v ps 2>&1 >/dev/null && command -v ps`
_wc=`command -v wc 2>&1 >/dev/null && command -v wc`
_printf=`command -v printf 2>&1 >/dev/null && command -v printf`
_mkdir=`command -v mkdir 2>&1 >/dev/null && command -v mkdir`
_rm=`command -v rm 2>&1 >/dev/null && command -v rm`

PID_PATH="${goodjob_dir}/tmp/pids"
GOODJOB_PID="${PID_PATH}/${name}.pid"
DAEMON_OPTS=" --daemonize --pidfile=${GOODJOB_PID} --poll-interval=${goodjob_poll_interval}"

start_cmd="${name}_start"
stop_cmd="${name}_stop"
restart_cmd="${name}_restart"
status_cmd="${name}_status"

###############################################################################
# Helper functions
###############################################################################

__pid=0
__status=0

_bundle=/usr/local/bin/bundle

goodjob_find_bundler(){

  # Try to check of rbenv is activated
  __rbenv_root=$(goodjob_execute 'echo $RBENV_ROOT')
  if [ x"${__rbenv_root}" != x ]; then
    _bundle=${__rbenv_root}/shims/bundle
  fi

  if [ ! -f $_bundle ]; then
    # clearing any custom path
    __oldpath=$PATH
    unset PATH
    export PATH=$__path

    _bundle=`command -v bundle 2>&1 >/dev/null && command -v bundle`
    unset PATH
    export PATH=$__oldpath
  fi

  if [ x"${_bundle}" = x ]; then
    $_printf 'Unable to find %s command\n' 'bundle'
    exit 1
  fi
}

goodjob_execute(){
  su -l ${goodjob_user} -c "cd ${goodjob_dir} && $1"
}

goodjob_execute_start() {
  goodjob_execute "RAILS_ENV=${goodjob_env} ${_bundle} exec good_job $DAEMON_OPTS"
}


goodjob_check_if_root(){
  if [ `id -u` -ne 0 ]; then
    ${_printf} 'Must be a root user (current is %s)\n' `whoami`
    exit 1
  fi
}

goodjob_check_if_running(){

  # checking if bundle gem is installed before doing anything
  goodjob_find_bundler

  # check if process is already running
  if [ -f $GOODJOB_PID ]; then
    __pid=`${_pgrep} -F $GOODJOB_PID`

    if [ x"${__pid}" != x ]; then
      __status=`${_ps} aux | ${_grep} ${__pid} | ${_grep} -v "grep" | ${_wc} -l`
    else
      __pid=0
    fi
  fi
}

###############################################################################
# Public functions
###############################################################################

goodjob_prestart_check(){
  goodjob_check_if_running

  # if process is already running, exit with code 1
  if [ ${__pid} -ne 0 ] && [ ${__status} -ne 0 ]; then
    ${_printf} '%s is already running...pid is %s\n' ${name} ${__pid}
    exit 1
  fi

  goodjob_execute "${_mkdir} -p $PID_PATH"

  goodjob_check_if_root
}

goodjob_prestop_check(){
  goodjob_check_if_running

  # if process is not running, exit with code 1
  if [ ${__pid} -eq 0 ] && [ ${__status} -eq 0 ]; then
    ${_printf} '%s not started\n' ${name}
    exit 1
  fi

  goodjob_check_if_root
}

goodjob_start(){
  goodjob_prestart_check

  goodjob_execute_start

  if [ $? -eq 0 ]; then
    ${_printf} '%s started\n' ${name}
  fi
}

goodjob_stop(){
  goodjob_prestop_check

  kill -QUIT `${_pgrep} -F ${GOODJOB_PID}`
  ${_printf} '%s stopped\n' ${name}
}

goodjob_restart(){
  goodjob_check_if_root

  ${_printf} 'Restarting %s service...\n' ${name}

  goodjob_check_if_running

  # check if goodjob service is running, if not then don't kill it
  if [ ${__pid} -ne 0 ] && [ ${__status} -ne 0 ]; then
    kill -QUIT `${_pgrep} -F ${GOODJOB_PID}`
  fi
  # start services normally
  goodjob_execute_start
  if [ $? -eq 0 ]; then
    ${_printf} 'Service %s restarted.\n' ${name}
  fi
}


goodjob_status(){

  goodjob_check_if_running

  # checking if goodjob is running
  if [ ${__pid} -ne 0 ] && [ ${__status} -ne 0 ]; then
    ${_printf} '%s service is running with pid %s\n' ${name} ${__pid}
  else
    ${_printf} '%s service is not running\n' ${name}
  fi
}

PATH="${PATH}:/usr/local/bin"
run_rc_command "$1"